<?php

namespace App\Recharge\Api;

use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Chengjuan extends AbstractApi
{
    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'timestamp'         => millisecondTimestamp(),
            'app_id'            => $bean->getSupplierNum(), //商户号
            'order_no'          => $bean->getOrderNo(), //订单号
            'recharge_number'   => $bean->getAccount(), //充值账号
            'product_id'        => $bean->getGoodsId(), //商品编码
            'amount'            => $bean->getRechargeNum() * $bean->getStartCharging(),
            'ip'                => $bean->getIp(),//获取用户当前的ip
            'notify_url'        => $bean->getNotifyUrl(), //异步回调地址
            'version'           => '1.0.0',
            'customer_price'    => $bean->getUnitPrice() * 100,
        ];
        ksort($array);
        $data_url = urldecode(http_build_query($array));
        $md5_str  = $data_url.'&key='. $bean->getSecretKey();
        $str      = md5($md5_str);
        $sign     = strtoupper($str);
        $array['sign'] = $sign;

        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('state', '');
        $order_sn = $request->input('order_no', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['SUCCESS', 'FAILURE']))->setRechargeSuccess($status == 'SUCCESS');
    }
}
